package cn.gson.crm.controller;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.codec.digest.DigestUtils;

/**
 * 公共servlet
 * 
 * @author gson
 *
 */
public abstract class BaseServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
	private HttpServletRequest request;
	private HttpServletResponse response;

	protected void errorForward(String message, String page) throws ServletException, IOException {
		request.setAttribute("error", message);
		forward(page);
	}

	protected void forward(String page) throws ServletException, IOException {
		request.getRequestDispatcher("/WEB-INF/jsp/" + page).forward(request, response);
	}

	protected void redirect(String path) throws IOException {
		String bathPath = (String) request.getAttribute("basePath");
		response.sendRedirect(bathPath + path);
	}

	protected void showError(Exception e) throws ServletException, IOException {
		showError(e.getMessage());
	}

	protected void showError(String message) throws ServletException, IOException {
		request.setAttribute("message", message);
		forward("error.jsp");
	}

	private void setRequestAndResponse(HttpServletRequest request, HttpServletResponse response) {
		this.request = request;
		this.response = response;
	}

	@Override
	protected void service(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		setRequestAndResponse(request, response);
		String method = request.getMethod();
		try {
			if ("get".equalsIgnoreCase(method)) {
				get(request, response);
			} else if ("post".equalsIgnoreCase(method)) {
				post(request, response);
			}
		} catch (Exception e) {
			e.printStackTrace();
			showError(e);
		}
	}

	protected void get(HttpServletRequest request, HttpServletResponse response) throws Exception {
		response.getWriter().append("请重写get请求处理！");
	}

	protected void post(HttpServletRequest request, HttpServletResponse response) throws Exception {
		response.getWriter().append("请重写post请求处理！");
	}
	
	//使用MD5隐藏密码
	protected String addPass(String password) throws Exception{
		password = new String(DigestUtils.md5(password),"utf-8");
		return password;
	}
}
